package com.cheyunkeji.er.activity.auction;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.adapter.auction.CooperatorListAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.auction.CooperatorBean;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 车商合作商列表
 */
public class CooperatorListActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener, AdapterView.OnItemClickListener {


    private static final String TAG = CooperatorListActivity.class.getSimpleName();

    //    每页数据量
    private static final int COUNTS_PER_PAGE = 10;

    //    搜索关键字
    private static String KEY_WORDS = null;

    //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
    private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    private static int selectedPosition = -1;
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.tv_search_content)
    TextView tvSearchContent;
    @BindView(R.id.ll_empty_content_display)
    LinearLayout llEmptyContentDisplay;
    @BindView(R.id.swipe_target)
    ListView swipeTarget;
    @BindView(R.id.swipe_layout)
    SwipeLayout swipeLayout;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.activity_cooperator)
    LinearLayout activityCooperator;

    //     当前页数
    private int CURRENT_LOAD_PAGE = 1;

    private ArrayList<CooperatorBean> dataList;
    private CooperatorListAdapter adapter;

    private Handler uiRefreshHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

                onRefreshSuccessed((ArrayList<CooperatorBean>) msg.obj);
            } else {

                onLoadMoreSuccessed((ArrayList<CooperatorBean>) msg.obj);
            }

        }
    };

    @Override
    protected void init() {
        KEY_WORDS = "";
        setContentView(R.layout.er_activity_cooperator);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        vTopbar.setTitle("合作门店/集团");
        vTopbar.setLeftBack();
        vTopbar.setRight("", R.mipmap.er_icon_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CooperatorListActivity.this, AddCooperatorActivity.class));
            }
        });

        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadMoreListener(this);
        swipeTarget.setOnItemClickListener(this);

    }

    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        adapter = new CooperatorListAdapter(dataList, this);
        swipeTarget.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        swipeLayout.setRefreshing(true);
        onRefresh();
    }

    @Override
    public void onRefresh() {

        CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
        CURRENT_LOAD_PAGE = 1;
        loadCarOwnerList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
        swipeLayout.setLoadMoreEnabled(true);
    }

    @Override
    public void onLoadMore() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
        loadCarOwnerList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
    }

    /**
     * 上拉加载成功刷新
     *
     * @param newList
     */
    private void onLoadMoreSuccessed(ArrayList<CooperatorBean> newList) {

        if (newList != null) {

            if (newList.size() != 0) {

                swipeLayout.endLoadMore();
                dataList.addAll(newList);
                adapter.notifyDataSetChanged();
                CURRENT_LOAD_PAGE++;

            } else {

                swipeLayout.endLoadMore();
                swipeLayout.setLoadMoreEnabled(false);

            }
        }

    }

    private void onRefreshSuccessed(ArrayList<CooperatorBean> newList) {

        if (newList != null && newList.size() != 0) {

            hideEmptyView();
            dataList.clear();
            dataList.addAll(newList);
            adapter.notifyDataSetChanged();
            CURRENT_LOAD_PAGE++;

        } else if (newList.size() == 0) {

            showContentEmptyView();
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
        swipeLayout.endRefresh();

    }

    private void hideEmptyView() {

        rlContent.setVisibility(View.VISIBLE);
        llEmptyContentDisplay.setVisibility(View.INVISIBLE);

    }

    private void showContentEmptyView() {

        rlContent.setVisibility(View.INVISIBLE);

        if(!TextUtils.isEmpty(KEY_WORDS)) {
            llEmptyContentDisplay.setVisibility(View.VISIBLE);
            tvSearchContent.setText(KEY_WORDS);
        }else{
            llEmptyContentDisplay.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 加载车商列表
     *
     * @param page
     * @param rows
     */
    public void loadCarOwnerList(int page, int rows) {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("page", String.valueOf(page));
        params.put("rows", String.valueOf(rows));

        ApiClient.postForm(HttpConstants.GET_CHANNEL_LIST, params, new RespCallback<List<CooperatorBean>>() {

            @Override
            protected void onRequestFailed(String msg) {

                SToast.show(msg);
            }

            @Override
            protected void onSuccess(List<CooperatorBean> data) {

                Log.e(TAG, "onSuccess: " + data.size());
                Log.e(TAG, "onSuccess: CURRENT PAGE INDEX : " + CURRENT_LOAD_PAGE);

                Message msg = uiRefreshHandler.obtainMessage();
                msg.obj = data;
                uiRefreshHandler.sendMessage(msg);

            }

            @Override
            public void onError(Exception e) {
                super.onError(e);

                if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                    swipeLayout.endRefresh();
                } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                    swipeLayout.endLoadMore();
                }
            }

        });

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(this,CooperatorProfileActivity.class);
        intent.putExtra("COOPERATOR_INFO",dataList.get(position));
        startActivity(intent);

    }

}
